package com.hcloud.system.user.service.impl;

import com.hcloud.common.crud.annon.HCloudPreAuthorize;
import com.hcloud.common.core.constants.CoreContants;
import com.hcloud.common.core.exception.ServiceException;
import com.hcloud.common.crud.service.impl.BaseDataServiceImpl;
import com.hcloud.system.api.bean.user.User;
import com.hcloud.system.user.entity.UserEntity;
import com.hcloud.system.user.repository.UserRepository;
import com.hcloud.system.user.service.UserService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Auther hepangui
 * @Date 2018/10/31
 */
@Service
public class UserServiceImpl extends
        BaseDataServiceImpl<UserEntity, UserRepository, User>
        implements UserService {

    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Override
    public User findByAccount(String account) {
        UserEntity byAccount = this.baseRepository.findByAccount(account);
        if(byAccount == null){
            throw new ServiceException("没有查到对用的用户:"+account);
        }
        User user = this.entityToBean(byAccount);
        return user;
    }

    @Override
    public void modifyPass(User user, String oldPsw, String newPsw) {
        if(user ==null || user.getId()==null ){
            throw new ServiceException("找不到用户");
        }
        UserEntity userEntity = this.get(user.getId());
        if(userEntity == null){
            throw  new ServiceException("找不到用户");
        }
        if(oldPsw!=null && passwordEncoder.matches(oldPsw,userEntity.getPassword())){
            userEntity.setPassword(passwordEncoder.encode(newPsw));
            this.update(userEntity);
        }else{
            throw new ServiceException("旧密码错误");
        }
    }

    @Override
    public void resetPass(String userId) {
        if(userId==null ){
            throw new ServiceException("找不到用户");
        }
        UserEntity userEntity = this.get(userId);
        if(userEntity == null){
            throw  new ServiceException("找不到用户");
        }
        userEntity.setPassword(passwordEncoder.encode(CoreContants.DEFAULT_PASSWORD));
        this.update(userEntity);
    }

    @Override
    public UserEntity add(UserEntity entity) {
        if(entity!=null && entity.getAccount()!=null){
            entity.setPassword(new BCryptPasswordEncoder().encode(CoreContants.DEFAULT_PASSWORD));
        }
        return super.add(entity);
    }

}
